package com.example.demo.service;

import com.example.demo.mapper.ChapterMapper;
import com.example.demo.entity.Chapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    // 根据课程 ID 获取章节列表（按顺序）
    public List<Chapter> findChaptersByCourseId(String courseId) {
        return chapterMapper.findByCourseIdOrderByOrder(courseId);
    }

    // 根据 ID 查找章节
    public Optional<Chapter> findChapterById(Integer chapterId) {
        return chapterMapper.findById(chapterId);
    }

    // 创建新章节
    public Chapter createChapter(Chapter chapter) {
        // 业务校验：确保关键字段不为空
        if (chapter.getCourseId() == null || chapter.getChapterName() == null) {
            throw new IllegalArgumentException("课程ID和章节名称不能为空");
        }

        // 插入操作，MyBatis 会将生成的 chapterId 填充回 chapter 对象
        if (chapterMapper.insert(chapter) > 0) {
            return chapter;
        } else {
            // 实际上由于使用了 @Options，插入失败的可能性主要是外键约束失败或数据库问题
            throw new RuntimeException("章节创建失败");
        }
    }

    // 更新章节
    public boolean updateChapter(Chapter chapter) {
        // 确保要更新的章节存在
        if (chapter.getChapterId() == null || !chapterMapper.findById(chapter.getChapterId()).isPresent()) {
            return false;
        }
        return chapterMapper.update(chapter) > 0;
    }

    // 删除章节
    public boolean deleteChapter(Integer chapterId) {
        return chapterMapper.deleteById(chapterId) > 0;
    }
}